# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '1476': {
        #  飞鱼支付 支付宝 2.6% 100-5000 witch
        'API_KEY': 'GFp6HSU70iwZGLKHckewIZOpKk8Fz4UW',
        'service_id': '10822',
        'gateway': 'http://pay8899.u2xu.com:38080/api/pay/payapply.htm',
        'query_gateway': 'http://pay8899.u2xu.com:38080/api/pay/payquery.htm',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_app_id(mch_id):
    return APP_CONF[mch_id]['appId']


def _get_service_id(mch_id):
    return APP_CONF[mch_id]['service_id']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(d, key):
    s = ''
    for k in sorted(d.keys()):
        if k not in ['user_id', 'svc_category']:
            s += '%s=%s&' % (k, d[k])
    s += '%s' % key
    _LOGGER.info("feiyupay sign string is: %s", s)
    return _gen_sign(s)


def generate_notify_sign(d, key):
    s = ''
    for k in sorted(d.keys()):
        if k in ['total_fee', 'out_trade_no_mch', 'version']:
            s += '%s=%s&' % (k, d[k])
    s += '%s' % key
    _LOGGER.info("feiyupay sign string is: %s", s)
    return _gen_sign(s)


def generate_query_sign(d, key):
    s = ''
    for k in sorted(d.keys()):
        if k in ['mch_id', 'out_trade_no_mch', 'timestamp', 'version']:
            s += '%s=%s&' % (k, d[k])
    s += '%s' % key
    _LOGGER.info("feiyupay sign string is: %s", s)
    return _gen_sign(s)


def generate_query_rsp_sign(d, key):
    s = ''
    for k in sorted(d.keys()):
        if k in ['code', 'out_trade_no_mch', 'payResult']:
            s += '%s=%s&' % (k, d[k])
    s += '%s' % key
    _LOGGER.info("feiyupay sign string is: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("feiyupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def verify_query_rsp_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_query_rsp_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("feiyupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 支付类型	pay_type 	 
# 微信-扫码	1000 	 
# 微信-wap	1001
# 微信-app	1002
# 支付宝-当面付	2000
# 支付宝-WAP	2001
# 支付宝-转账	2002
# 网银	5000
# 快捷	5001
# 银联扫码	5002
def _get_pay_type(service):
    if service == 'alipay_h5':
        return '2001'
    elif service == 'alipay_face2face':
        return '2000'
    elif service == 'alipay_trans':
        return '2002'
    return '2001'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '219.135.56.195'


def _get_device_id(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_id') or 'IMEI00000001111112222222'


def _check_valid_ip_address(request):
    if request.META['REMOTE_ADDR'] not in ['123.176.96.130', '210.5.58.146', '103.230.243.38']:
        raise ParamError('unvalid ip address')


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)

    parameter_dict = OrderedDict((
        ('mch_id', app_id),
        ('service_id', _get_service_id(app_id)),
        ('pay_type', _get_pay_type(service)),
        ('total_fee', str(int(pay_amount * 100))),
        ('title', 'FlyFish'),
        ('description', 'charge'),
        ('out_trade_no_mch', str(pay.id)),
        ('notify_url', '{}/pay/api/{}/feiyupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('callback_url', '{}/pay/api/{}/feiyupay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('timestamp', int(round(time.time() * 1000))),
        ('ip', _get_device_ip(info)),
        ('user_id', str(pay.user_id)),
        ('svc_category', '1'),
        ('version', '1'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("feiyupay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['out_trade_no_mch'])
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_gateway(app_id), json=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("feiyupay create rsp data: %s %s", response.status_code, response.text)
    data = json.loads(response.text)
    return {'charge_info': data['payUrl']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _check_valid_ip_address(request)
    data = json.loads(request.body)
    _LOGGER.info("feiyupay notify data: %s, order_id is: %s", data, data['out_trade_no_mch'])
    verify_notify_sign(data, api_key)
    pay_id = data['out_trade_no_mch']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('feiyupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = str(data['out_trade_no'])
    total_fee = float(data['total_fee']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 支付状态,00-交易成功
    if trade_status == '0':
        _LOGGER.info('feiyupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mch_id', app_id),
        ('out_trade_no_mch', str(pay_id)),
        ('timestamp', local_now().strftime('%Y-%m-%d %H:%M:%S')),
        ('version', '1')
    ))
    parameter_dict['sign'] = generate_query_sign(parameter_dict, api_key)
    _LOGGER.info("feiyupay query data: %s, order_id: %s", json.dumps(parameter_dict),
                 parameter_dict['out_trade_no_mch'])
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_query_gateway(app_id), json=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("feiyupay query rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)['data']
        verify_query_rsp_sign(data, api_key)
        trade_status = str(data['payResult'])
        trade_no = str(data['out_trade_no'])
        total_fee = float(data['fee']) / 100.0
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        if trade_status == '0':
            _LOGGER.info('feiyupay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('feiyupay data error, status_code: %s', response.status_code)
